package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.pojo.Setmeal;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R selectAll(int page, int pageSize) {

        Page<Category> page1 = new Page<>(page, pageSize);
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("sort");
        wrapper.orderByDesc("update_time");

        categoryService.page(page1, wrapper);
        return R.success(page1);
    }

    /**
     * 添加
     *
     * @param category
     * @return
     */
    @PostMapping
    public R ADD(@RequestBody Category category) {

        categoryService.save(category);
        return R.success("添加成功");
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R delete(Long ids) {

        //根据id获取当前数据中的type
        Integer type = categoryService.getById(ids).getType();

        if (type == 1) {

            QueryWrapper<Dish> wrapper = new QueryWrapper<>();

            wrapper.eq("category_id", ids);
            //根据id查询
            int count = dishService.count(wrapper);

            if (count > 0) {
                return R.error("宝,乖.这个不能删");
            }
        } else {
            QueryWrapper<Setmeal> wrapper = new QueryWrapper<>();

            wrapper.eq("category_id", ids);
            int count = setmealService.count(wrapper);
            if (count > 0) {
                return R.error("再乱删头打歪");
            }
        }
        categoryService.removeById(ids);

        return R.success("删除成功");
    }

    /**
     * 修改
     *
     * @param category
     * @return
     */
    @PutMapping
    public R update(@RequestBody Category category) {


        categoryService.updateById(category);

        return R.success("修改成功");

    }
    @GetMapping("/list")
    public R cateGory(Integer type){

        QueryWrapper<Category> wrapper =new QueryWrapper<>();
        if(type!=null){
            wrapper.eq("type",type);
        }

        List<Category> list = categoryService.list(wrapper);
        return R.success(list);
    }


}
